package com.yunxiao.cloud.common.exception;

import com.yunxiao.cloud.common.base.BaseResultResponse;
import com.yunxiao.cloud.common.constant.ExceptionConstant;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.security.sasl.AuthenticationException;
import javax.servlet.http.HttpServletRequest;

/**
 * @description: GlobalExceptionHandler
 * @date: 2019/12/16 11:30
 * @author: yunxiao
 * @version: 1.0
 */
@RestControllerAdvice
public class GlobalExceptionHandler {
    private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    @ExceptionHandler(value = Exception.class)
    public Object systemException(HttpServletRequest request, Exception exception) {
        //按需重新封装需要返回的错误信息
        BaseResultResponse result = new BaseResultResponse();

        if (exception instanceof MethodArgumentNotValidException){
            logger.error("参数异常", exception);
            result.setCode(ExceptionConstant.DATA_WRITE_FAIL_CODE);
            result.setMessage(ExceptionConstant.DATA_WRITE_FAIL_MSG);
        } else if (exception instanceof HttpMessageNotReadableException) {
            logger.error("输入参数异常", exception);
            result.setCode(ExceptionConstant.DATA_WRITE_FAIL_CODE);
            result.setMessage(ExceptionConstant.DATA_WRITE_FAIL_MSG);
        } else if (exception instanceof AuthenticationException) {
            logger.error("没有权限，请联系管理员授权", exception);
            result.setCode(ExceptionConstant.ERROR_NOT_AUTHORIZED);
            result.setMessage(ExceptionConstant.ERROR_NOT_AUTHORIZED_MSG);
        } else if (exception instanceof BusinessParamCheckingException) {
            BusinessParamCheckingException bpe = (BusinessParamCheckingException) exception;
            logger.error("BusinessParamCheckingException ", exception);
            result.setCode(bpe.getCode());
            result.setMessage(bpe.getReason());
        } else if (exception instanceof BusinessRuntimeException) {
            BusinessRuntimeException bre = (BusinessRuntimeException) exception;
            logger.error("BusinessRuntimeException ", exception);
            result.setCode(bre.getCode());
            result.setMessage(bre.getReason());
        } else {
            logger.error("未处理的业务处理异常", exception);
            result.setCode(ExceptionConstant.SERVICE_SYSTEM_ERROR_CODE);
            result.setMessage(ExceptionConstant.SERVICE_SYSTEM_ERROR_MSG);
        }
        return result;
    }
}
